﻿using System.Collections.Specialized;
using Newtonsoft.Json;

namespace CometDocs
{
    internal partial class Client
    {
        /// <summary>
        /// Refresh an authentication token to be used longer than the initial validity: https://www.cometdocs.com/developer/apiDocumentation#method-refreshToken
        /// </summary>
        /// <param name="token">The authentication token to refresh.</param>
        /// <param name="validity">The new validity for the token.</param>
        public void RefreshToken(AuthenticationToken token, int? validity = null)
        {
            NameValueCollection @params = new NameValueCollection(2);
            @params.Add("token", token.Value);
            if (validity != null)
            {
                @params.Add("validity", validity.ToString());
            }

            byte[] result = webClient.UploadValues(APIRoot + "refreshToken", @params);

            string json = encoding.GetString(result);

            Response response = JsonConvert.DeserializeObject<Response>(json);

            CheckAndThrow(response);
        }
    }
}
